package com.situ.mall.controller;

import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.query.UserQuery;
import com.situ.mall.service.IUserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/page")
public class PageController {

    @Autowired
    private IUserService userService;




    /**
     * /page/user/add     /page/login
     *
     * @return
     */
    @RequestMapping("/**")
    public String path(HttpServletRequest request, Model model) {

        // 登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (ObjectUtils.isEmpty(user)) {
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            for (Cookie c : cookies) {
                String name = c.getName();
                if ("autoLoginPortal".equals(name)) {
                    cookie = c;
                    break;
                }
            }
            if (!ObjectUtils.isEmpty(cookie)) {
                String[] values = cookie.getValue().split("&");
                UserQuery userQuery = new UserQuery();
                userQuery.setAccount(values[0]);
                userQuery.setPassword(values[1]);
                User login = userService.login(userQuery.getAccount(), userQuery.getPassword());
                if (!ObjectUtils.isEmpty(login)) {
                    session.setAttribute("user", login);
                }
            }
        }

        String requestURI = request.getRequestURI();
        System.out.println("requestURI: " + requestURI);

        String queryString = request.getQueryString();
        String returnUri = queryString == null ? requestURI : requestURI + "?" + queryString;
        model.addAttribute("returnUri", returnUri);

        String[] paths = requestURI.split("/");
        //["","page","user","list"]
        //["","page","login"]
        if (paths.length == 4) {
            return paths[2] + "_" + paths[3];
        } else if (paths.length == 3) {
            return paths[2];
        } else {
            return "index";
        }
    }
}